package com.example.demo.controller;

import com.aliyuncs.exceptions.ClientException;
import com.example.demo.entity.Home;
import com.example.demo.service.HomeService;
import com.example.demo.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/student")
public class HomeController {
    @Autowired
    private HomeService homeService;

    @Autowired
    private SmsService smsService;

    @PostMapping("/send-home")
    public ResponseEntity<String> sendHome(@RequestBody Home request) throws ClientException {
        String templateParam = "{\"name\":\"" + request.getName() + "\",\"type\":\"" + request.getType() + "\",\"address\":\"" + request.getAddress() + "\"}";
        System.out.println(templateParam);
        boolean isSent = smsService.sendSms(request.getPhone(), templateParam);
        boolean isSend = homeService.sendToHome(request.getId(), request.getName(), request.getType(), request.getNum(), request.getPhone(), request.getSmscontent(), request.getAddress());
        if (isSend&&isSent) {
            return ResponseEntity.ok("短信发送请求已接受，正在处理");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("短信发送请求失败");
        }
    }

    @GetMapping("/get-home-data")
    public List<Home> getAll() {
        return homeService.getAll(); // 获取所有记录
    }

    @PostMapping("/find")
    public ResponseEntity<String> updateIsFind(@RequestParam String smsTime,@RequestParam String type, @RequestParam int isfind) {
        try {
            boolean success = homeService.isFindStudent(smsTime,type,isfind);
            if (success) {
                return ResponseEntity.ok("更新成功");
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到相关记录");
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器错误");
        }
    }
    // 删除特定时间和类型的短信记录
    @DeleteMapping("/delete")
    public ResponseEntity<String> deleteRecord(@RequestParam String smstime, @RequestParam String type) {
        try {
            homeService.deleteisFindStudent(smstime, type);
            return ResponseEntity.ok("短信记录删除成功");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("删除短信记录失败");
        }
    }
}
